const mongoose = require('mongoose')
const db = 'mongodb://localhost/koavant'
const glob = require('glob')
const {resolve} = require('path')

// mongoose.Promise = global.Promise

// 载入所有Schema
exports.initSchemas = () =>{
  glob.sync(resolve(__dirname,'./schema/','**/*.js')).forEach(require)
}

exports.connect = () =>{
  // 连接数据库
  mongoose.connect(db)
  let maxConnectTimes = 0

  return new Promise((resolve,reject)=>{
    // 增加数据库连接监听事件
    mongoose.connection.on('disconnected', () => {
      // 重连3次
      if (maxConnectTimes<3) {
        maxConnectTimes++
        mongoose.connect(db)
      }else{
        reject()
        throw new Error('数据库出错，请联系开发者……')
      }
    })
    // 数据库出现错误时
    mongoose.connection.on('error', err => {
      // 重连3次
      if (maxConnectTimes < 3) {
        maxConnectTimes++
        mongoose.connect(db)
      } else {
        reject()
        throw new Error('数据库出错，请联系开发者……')
      }
    })
    // 连接成功
    mongoose.connection.once('open', () => {
      console.log('数据库连接成功');
      resolve()
    })
  })
}